package com.xz.courseschedule.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5 encryption utility class
 */
public class MD5Utils {

    /**
     * Encrypt string with MD5
     * @param input string to be encrypted
     * @return 32-bit lowercase MD5 string
     */
    public static String encrypt(String input) {
        try {
            // Get MD5 encryption algorithm instance
            MessageDigest md = MessageDigest.getInstance("MD5");
            // Convert input string to byte array and encrypt
            byte[] messageDigest = md.digest(input.getBytes());
            // Convert byte array to hexadecimal string
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 encryption failed", e);
        }
    }

    /**
     * Verify if password matches
     * @param plainText plain text password
     * @param encryptedText encrypted password
     * @return whether it matches
     */
    public static boolean verify(String plainText, String encryptedText) {
        return encrypt(plainText).equals(encryptedText);
    }
}